<template>
  <div class="video-container">
    <div class="video-left-board">
      <div class="video-left-board-top">
        <div style="padding-top: 2px;padding-left:5px;">
          <el-input
            v-model="queryParams.vehicleId"
            placeholder="可查询车辆标识"
            clearable
            style="width: 76%;"
            @clear="handleQuery"/>
          <el-button  style="" icon="el-icon-search"  @click="handleQuery"></el-button>
        </div>
      </div>
      <div class="video-left-board-down">
        <el-tree
          ref="myTree"
          :data="treeData"
          :props="props"
          node-key="id"
          :highlight-current="true"
          :load="loadNode"
          :render-content="renderContent"
          lazy
          @node-click="handleNodeClick">
        </el-tree>
      </div>
    </div>

    <div class="video-center-board"  id="map-board">

    </div>
    <div>
      <div v-show="loading" class="shade"></div>

      <div v-show="loading"  class="dialog">
        <img src="../../../assets/gif/loading.gif">
      </div>
    </div>
  </div>
</template>

<script>

import {
  carDevLocationQuery,
  getCarDevTreeNoCHn,
  getCarDevTreeNoCHnByVehicleId,
  locationQuery
} from "@/api/buss/realTimeGps";
import AMapLoader from "@amap/amap-jsapi-loader";
import icon from '../../../assets/images/map-car.png';

export default {
  name: "RealTimeGps",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 车辆设备树
      props: {
        id: 'id',
        carDevId: 'carDevId',
        label: 'label',
        carDevStatus: 'carDevStatus',
        whetherCompanyNode: 'whetherCompanyNode',
        whetherCarDevNode: 'whetherCarDevNode',
        whetherCarDevChnNode: 'whetherCarDevChnNode',
        isLeaf: 'whetherLastLevelNode'
      },
      renderContent(h, { node, data }) {
        if(data.whetherCarDevNode){
          if("01" === data.carDevStatus){
            return (
              <span>
              <svg-icon icon-class="car-online"/>
              <span style="margin-left:3px">{node.label}</span>
            </span>);
          }else {
            return (
              <span>
              <svg-icon icon-class="car-offline"/>
              <span style="margin-left:3px">{node.label}</span>
            </span>);
          }
        }else {
          return (
            <span>
              <i class={node.icon}/>
              <span>{node.label}</span>
            </span>);
        }
      },
      propParams: {
        id: null,
        yesNotCarDevNode: null
      },
      map: null,//地图
      marker: null,//地图标记
      currentLocation: null,//当前定位
      selectCarDevId: null,//选择的车辆设备id
      newIcon: null,//定位图标
      // 查询参数
      queryParams: {
        vehicleId: null
      },
      // 发送车辆实时位置查询命令参数
      carDevLocationQueryParams: {
        carDevId: null
      },
      // 查询车辆实时位置参数
      locationQueryParams: {
        carDevId: null,
        flowId: null
      },
      intervalvvv: null,//循环定时任务
      treeData: []
    }
  },
  watch: {
  },
  created() {
    this.initMap();
  },
  methods: {
    loadNode(node, resolve) {
      if (node === null || node === undefined || node.level === 0){
        this.propParams.id = null;
        this.propParams.whetherCarDevNode = false;
        getCarDevTreeNoCHn(this.propParams).then(response => {
          this.treeData = response.data;
        });
      }else{
        if (node.data.isLeaf === true){
          return resolve([]);
        }
        this.propParams.id = node.data.id;
        this.propParams.whetherCarDevNode = node.data.whetherCarDevNode;
        this.propParams.whetherCompanyNode = node.data.whetherCompanyNode;

        getCarDevTreeNoCHn(this.propParams).then(response => {
          if(node.data.whetherCompanyNode){
            var label  = node.data.label;
            var label1 = label.split("(")[0];
            var label2 = response.data[0].onlineStatusCount;
            node.data.label = label1+label2;
          }
          return resolve(response.data);
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if(this.queryParams.vehicleId === null || this.queryParams.vehicleId === ''|| this.queryParams.vehicleId.trim() === ''){
          this.loadNode();
      }else {
        getCarDevTreeNoCHnByVehicleId(this.queryParams).then(response => {
          this.treeData = response.data;
        });
      }
    },
    initMap(){
      AMapLoader.load({
        key: process.env.VUE_APP_MAP_KEY,
        version: "2.0",
        plugins: ['AMap.GeoJSON', 'AMap.Marker'] // 引入地理定位和标记点插件
      }).then((AMap) => {
        // 调用地图渲染函数
        // renderMap(AMap);
        this.map = new AMap.Map("map-board", {  //设置地图容器id
          rotateEnable:true,
          pitchEnable:true,
          zoom: 17,//初始化地图级别
          pitch: 50,
          rotation: -15,
          viewMode:'3D', //开启3D视图,默认为关闭
          zooms:[2,20],
          center: this.currentLocation //初始化地图中心点位置
          //
          // viewMode: "3D",    //是否为3D地图模式
          // zoom: 12,           //初始化地图级别
          // center: this.currentLocation
        });

        // 创建自定义图标
        this.newIcon = new AMap.Icon({
          size: new AMap.Size(35, 20), // 图标尺寸
          image: icon, // 图标的URL
          imageSize: new AMap.Size(35, 20), // 图标图片尺寸
        });

        // 添加自定义图标标记
        this.marker = new AMap.Marker({
          position: this.currentLocation,
          icon: this.newIcon,
          offset: new AMap.Pixel(-25, -25)
        });
        this.map.add(this.marker);

      }).catch((e) => {
        console.error(e); //加载错误提示
      });
      // const renderMap = (AMap) => {
      //   this.map = new AMap.Map("video-right-board-top", {
      //     zoom: 12,
      //     center: this.currentLocation
      //   });
      // };
    },
    locationQueryFunction(locationQueryParams){
      return new Promise(resolve => {
        setTimeout(() => {
          // 这里是延迟后要执行的代码
          locationQuery(locationQueryParams).then(res => {
            resolve(res);
          });
        }, 1000); // 暂停1秒钟（1000毫秒）
        //此接口为循环调用的接口，按照自己的需要进行修改
        // locationQuery(locationQueryParams).then(res => {
        //   resolve(res);
        // });
      });
    },
    //循环定时任务
    interval(){
      carDevLocationQuery(this.carDevLocationQueryParams).then(async response => {
        this.locationQueryParams.flowId = response.data;
        for (let i = 0; i < 10; i++) {
          let resData = await this.locationQueryFunction(this.locationQueryParams);
          if(resData != null && resData.data != null){
            this.map.remove(this.marker);
            this.currentLocation = [resData.data.longitude, resData.data.latitude];
            this.map.setCenter(this.currentLocation);
            this.marker = new AMap.Marker({
              position: this.currentLocation,
              icon: this.newIcon,
              offset: new AMap.Pixel(-10, -10)
            });
            this.map.add(this.marker);
            this.loading = false;
            break;
          }else {
            window.clearInterval(this.intervalvvv);//清除循环定时任务
          }
        }
      }).catch(error => {
        this.loading = false;
        console.log(error);
        window.clearInterval(this.intervalvvv);//清除循环定时任务
      });
    },
    //开始循环定时任务
    startInterval(){
      this.intervalvvv = window.setInterval(this.interval,10000);
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.loading = true;
      const tree = this.$refs.myTree;
      if(data.whetherCarDevNode){
        if("01" === data.carDevStatus){
          this.selectCarDevId = data.id;
          this.carDevLocationQueryParams.carDevId = data.id;
          this.locationQueryParams.carDevId = data.id;
          if (tree) {
            tree.setCurrentKey(data.id);
          }
          window.clearInterval(this.intervalvvv);//清除循环定时任务
          this.clearAllMarkers();
          this.interval();
          this.startInterval();
        }else {
          this.loading = false;
          this.selectCarDevId = null;
          tree.setCurrentKey(null);
          this.$message({
            message: '该设备未在线',
            type: 'warning'
          });
        }
      }else {
        tree.setCurrentKey(null);
        this.selectCarDevId = null;
        this.loading = false;
      }
    },
    // 清除所有标记点的函数
    clearAllMarkers() {
      // 获取地图上的所有覆盖物
      var overlayList = this.map.getAllOverlays('marker');
      // 遍历并移除
      overlayList.forEach(function(overlay){
        overlay.setMap(null);
      });
    },
  }
}
</script>

<style lang='scss' scoped>

.shade{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}
.dialog{
  z-index: 891016; top: 45%; left: 50%;position:fixed;
}
.video-button{
  background-color: #e6a23c;
  color: white;
  height: 36px;
  margin-left: 10px
}
.video-select{
  width: 130px;
  margin-left:10px;
  font-size: 12px;
}
.video-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 84px);
}

.video-left-board {
  width: 260px;
  position: absolute;
  left: 0;
  top: 0;
  height: calc(100vh - 84px);
}

.video-left-board-top{
  background-color: #E8EAED;
  position: relative;
  height: 42px;
  //background: #fff;
  border-bottom: 1px solid rgb(214, 214, 214);
  border-right: 1px solid rgb(214, 214, 214);
  box-sizing: border-box;
}

.video-left-board-down{
  border-right: 1px solid rgb(214, 214, 214);
  overflow: auto;
  position: relative;
  height: calc(100vh - 126px);
  background: #fff;
  box-sizing: border-box;
}
/* 设置::-webkit-scrollbar可以让滚动条消失，但仍可以滚动 */
//.video-left-board-down::-webkit-scrollbar {
//  display:none
//}
.video-center-board {
  height: calc(100vh - 84px);
  width: auto;
  margin: 0 0 0 260px;
  box-sizing: border-box;
}

</style>
